from datetime import datetime
from sqlalchemy import Column, Integer, String, DateTime, DECIMAL, Enum, ForeignKey, Text
from sqlalchemy.orm import relationship
from werkzeug.security import generate_password_hash, check_password_hash
from extension import db


# 用户表
class User(db.Model):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    username = Column(String(50), unique=True, nullable=False, comment='用户名')
    password_hash = Column(String(256), nullable=False, comment='密码哈希')
    created_at = Column(DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')

    # 关联关系
    carts = relationship('Cart', backref='user', lazy=True, cascade='all, delete-orphan')
    orders = relationship('Order', backref='user', lazy=True, cascade='all, delete-orphan')

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def verify_password(self, password):
        return check_password_hash(self.password_hash, password)


# 商品表
class Product(db.Model):
    __tablename__ = 'products'
    id = Column(Integer, primary_key=True)
    name = Column(String(255), nullable=False, comment='商品名称')
    category = Column(String(255), nullable=False, comment='商品分类')
    price = Column(DECIMAL(10, 2), nullable=False, comment='商品价格')
    image = Column(String(255), comment='商品图片链接')
    created_at = Column(DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')

    # 关联关系：订单商品关联表
    order_products = relationship('OrderProduct', backref='product', lazy=True)


# 购物车表
class Cart(db.Model):
    __tablename__ = 'carts'
    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('users.id'), nullable=False, comment='用户 ID')
    product_id = Column(Integer, ForeignKey('products.id'), nullable=False, comment='商品 ID')
    quantity = Column(Integer, nullable=False, default=1, comment='商品数量')
    created_at = Column(DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')


# 订单表
class Order(db.Model):
    __tablename__ = 'orders'
    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('users.id'), nullable=False, comment='用户 ID')
    recipient_name = Column(String(50), nullable=False, comment='收货人姓名')
    recipient_phone = Column(String(20), nullable=False, comment='收货人手机号')
    shipping_address = Column(Text, nullable=False, comment='收货地址')
    order_number = Column(String(32), unique=True, nullable=False, comment='订单号', default=lambda: f"ORD-{datetime.now().strftime('%Y%m%d%H%M%S')}-{id}")
    subtotal = Column(DECIMAL(10, 2), nullable=False, comment='商品总价')
    total_amount = Column(DECIMAL(10, 2), nullable=False, comment='订单总金额')
    shipping_fee = Column(DECIMAL(10, 2), nullable=False, default=0, comment='运费')
    coupon_discount = Column(DECIMAL(10, 2), nullable=False, default=0, comment='优惠券减免')
    order_status = Column(
        Enum('待支付', '已支付', '待发货', '待收货', '已完成', '已取消'),
        nullable=False,
        default='待支付',
        comment='订单状态'
    )
    payment_method = Column(
        Enum('苹果支付', '微信支付', '支付宝', '银行卡支付'),
        comment='支付方式'
    )
    payment_time = Column(DateTime, comment='支付时间')
    transaction_id = Column(String(50), comment='交易单号')
    created_at = Column(DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')

    # 关联关系：订单与商品的多对多关联
    order_products = relationship('OrderProduct', backref='order', lazy=True, cascade='all, delete-orphan')

# 订单与商品关联表（原订单详情表重命名）
class OrderProduct(db.Model):
    __tablename__ = 'order_products'
    id = Column(Integer, primary_key=True)
    order_id = Column(Integer, ForeignKey('orders.id'), nullable=False, comment='订单 ID')
    product_id = Column(Integer, ForeignKey('products.id'), nullable=False, comment='商品 ID')
    quantity = Column(Integer, nullable=False, comment='商品数量')
    price = Column(DECIMAL(10, 2), nullable=False, comment='商品单价')
    subtotal = Column(DECIMAL(10, 2), nullable=False, comment='商品小计')
    created_at = Column(DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')
